var util = require('../../utils/util2')
//将天气信息添加入数据库
function addWeather() {
    wx.cloud
        .callFunction({
            name: "getopenid",
        })
        .then((res) => {
            let openid = res.result.openid;
            // wx.setStorageSync("openid", openid);
            // console.info(openid)
            util.getUserLocation()
            var weather = wx.getStorageSync('weather')
            let weatherMessage = "天气" + weather.weather + "当前气温" + weather.temp + "℃" + "详情点击查看"
            //将天气信息添加数据库
            wx.cloud
                .database()
                .collection("userInfo")
                .where({
                    openid: openid
                })
                .update({
                    data: {
                        weatherMessage: weatherMessage,
                    }
                })
                .then((res) => {
                    console.log("添加天气信息成功", res);
                })
                .catch((res) => {
                    console.log("添加天气信息失败", res);
                });
        })
        .catch((res) => {
            console.log("获取openid失败", res);
        });
   
}
Page({
    //获取用户的openid
    getOpenid() {
        wx.cloud
            .callFunction({
                name: "getopenid",
            })
            .then((res) => {
                let openid = res.result.openid;
                this.setData({
                    openid: openid,
                });
                console.log("获取openid成功", openid);
                //this.sendAll(openid)
                this.getUserProfile();
                this.getDBInfo(openid);
            })
            .catch((res) => {
                console.log("获取openid失败", res);
            });
    },
    getUserProfile() {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: "展示用户信息", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res);
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true,
                });
            },
        });
    },
    addInfo() {
        wx.cloud
            .database()
            .collection("userInfo")
            .add({
                data: {
                    openid: this.data.openid,
                    avatarUrl: this.data.userInfo.avatarUrl,
                    city: this.data.userInfo.city,
                    country: this.data.userInfo.country,
                    gender: this.data.userInfo.gender,
                    nickName: this.data.userInfo.nickName,
                    province: this.data.userInfo.province,
                }
            })
            .then((res) => {
                console.log("添加用户信息成功", res);
            })
            .catch((res) => {
                console.log("添加用户信息失败", res);
            });
    },
    getDBInfo(openid) {
        wx.cloud
            .database()
            .collection("userInfo")
            .where({
                openid: wx.cloud.database().command.eq(openid)
            })
            .get()
            .then((res) => {
                console.log("获取用户信息成功", res);
                this.setData({
                    openid: res.data[0].openid,
                    avatarUrl: res.data[0].avatarUrl,
                    city: res.data[0].city,
                    country: res.data[0].country,
                    gender: res.data[0].gender,
                    nickName: res.data[0].nickName,
                    province: res.data[0].province,
                });
                let nickName = res.data[0].nickName
                console.log("获取用户信息成功", nickName);
            })
            .catch((res) => {
                console.log("获取用户信息失败，请添加用户信息", res);
                // 如果数据库没有openid信息，添加用户信息
                this.addInfo();
            });
    },
    //发送模板消息到多个用户,推送之前要先获取用户的openid
    sendAll() {
        wx.cloud
            .database()
            .collection("userInfo")
            .get()
            .then((res) => {
                let userInfo = res.data
                console.log("获取所有用户信息成功", userInfo);
                userInfo.forEach((item) => {
                    console.log("推送一个消息成功", item.openid);
                    this.sendFun(item.openid);
                });
            })
            .catch((res) => {
                console.log("推送消息失败", res);
            });
    },
    sendFun(openid) {
        wx.cloud
            .callFunction({  // sendMsg
                name: "pushNotify",
                data: {
                    openid: openid,
                    // weatherMessage: weatherMessage,
                }
            })
            .then((res) => {
                console.log("推送消息成功", res);
            })
            .catch((res) => {
                console.log("推送消息失败", res);
            });
    },
    /**
   * 启动定时器
   */
    startInter: function () {
        var that = this;

        that.data.inter = setInterval(
            function () {
                // TODO 你需要无限循环执行的任务
                addWeather();
                console.log('setInterval 每过一个小时执行一次天气信息添加入数据库任务')
            }, 7200000);
    },
    /** 
     * 结束定时器
     */
    endInter: function () {
        var that = this;
        that.clearInterval(that.data.inter)
    },
    shouquan() {
        wx.requestSubscribeMessage({
            tmplIds: ["你自己的模板id"],
            //这里填入我们生成的模板id
            success(res) {
                console.log("授权成功", res);
            },
            fail(res) {
                console.log("授权失败", res);
            },
        });
    },
    //授权提示弹窗
    onShowModal() {
        wx.showModal({
            title: '授权确认',
            content: '为了获得更好的使用体验，需要用户授权，点击确认按钮进行授权(务必勾选总保持以上选择)',
            cancelText: "取消",
            cancelColor: "#00f",
            confirmText: "确认",
            confirmColor: "#f00",
            complete: (res) => {
                if (res.cancel) {
                    this.onShowToast();
                }
                if (res.confirm) {
                    console.log("test1:")
                    this.shouquan();
                    // setTimeout(shouquan, 3000);
                    // setTimeout(saveShouquanTimes, 10000);
                }
            }
        })
        // this.sendAll();
    },
    onShowToast() {
        wx.showToast({
            title: '授权失败',
            icon: "error",
            duration: 3000,
            mask: true,
            success() {
                console.log("显示成功");
            },
            fail() {
                console.log("显示失败");
            },
            complete() {
                console.log("complete");
            }
        })
    },
    /**
     * 页面的初始数据
     */
    data: {},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getOpenid();
        this.onShowModal();
        // this.startInter();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() { },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() { },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() { },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() { },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() { },
});
